<?php
namespace app\office\controller;

use think\Request;
use think\Db;
use app\office\controller\OfficeBase;
use app\office\model\Document as DocumentModel;
use app\office\model\ModuleStatic as ModuleStaticModel; 
use app\office\model\documentProcess;

class Document extends OfficeBase
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    // protected $filter=[];
    public function index()
    {
      //验证Cookie↓
      $this->checkCookie();
      // 引入navbar
      $this->setNavbar();
      $this->assign('title',"设计文件列表");
      // 引入文件阶段option选择值
      $staticOptionList=ModuleStaticModel::where('module','document')->order('static','asc')->column('static_title,static,module','static');
      $this->assign('staticOptionList',$staticOptionList);
      // 此处进行数据筛选;
      if(!input('?request.')){
        $data=input('request.');
        // 获取筛选数组
        $target=array('is_sth','sth_num','max_static',);
        $filter=$this->getFilter($data,$target);
        // 获取排序数组
        $order=input('?request.order')?input('request.order/a'):array(''=>'');
        
        // dump($data);
        // $timeRange=['start_time','end_time'];
        // $result=$this->getDateRange($data,$timeRange);
        // dump($result);
        // $filter=array_merge($filter,$result);
        // dump($filter);
      }
      // 此处重置reset筛选
      if(input('?request.reset')){
        $filter=array();
      }
      $query=array_merge($filter,array('order'=>$order));                     /* query用来传递数据 */
      $list=DocumentModel::scope('static')->where($filter)->order(key($order),current($order))->paginate(10,false,['query' =>$query]);   /* 这里用的是查询构建器的select()方法;或者可以使用模型的all()方法,$list=DocumentModel::all(); */
      $countall=DocumentModel::scope('static')->where($filter)->count();
      $this->assign('query',$query);
      $this->assign('list',$list);
      $this->assign('count',count($list));
      $this->assign('countall',$countall);
      return $this->fetch();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create(Request $request)
    {
      //验证Cookie↓
      $this->checkCookie();
      // 引入navbar
      $this->setNavbar();
      $this->assign('title',"设计文件创建");
      // 获取设计文件编号
      $code=$this->makeCode('document');
      $this->assign('code',$code);
      return $this->fetch();
    }


    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
      $document=new DocumentModel;
      // 保存图片类文件
      if($file = $request->file('pic')){
        $document->pic_name=$this->savePic($file);
      }
      // 验证并保存文件
      if($document->allowField(true)->validate(true)->save(input('post.'))){
        $this->success('设计文件'.$document->code.":".$document->title.'新增成功','index');
      }else{
        return $document->getError();
      }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
      //验证Cookie↓
      $this->checkCookie();
      // 引入navbar
      $this->setNavbar();
      $this->assign('title',"设计文件信息");
      $document=DocumentModel::get($id);
      $this->assign('document',$document);
      //此处开始进行流程信息的获取从document_process 中获取信息
      $documentProcess=$document->documentProcess()->where('is_fixed',1)->order('id','asc')->select();
      // dump($documentProcess);
      $this->assign('documentProcess',$documentProcess);
      $this->assign('documentProcessNum',count($documentProcess));
      return $this->fetch();
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(Request $request,$id)
    {
      //验证Cookie↓
      $this->checkCookie(); 
      // 引入navbar
      $this->setNavbar();
      $this->assign('title',"设计文件编辑");
      $document=DocumentModel::get($id);     /* ->getData()后面的getData()是在定义了获取器的情况下来获得原始数据 */
      //验证用户是否有权限修改数据
      if($request->cookie('login_code')!==$document->create_code){
        $this->error('仅文件创建者可修改,请联系管理员','read?id='.$id,"",2);
      }
      $this->assign('document',$document);
      return $this->fetch();
    }
    
    
    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
      $data = input('post.');
      $document = DocumentModel::get($id);
      // 注意,下面获取post的数组,需要说明,加了"/a"↓
      $documentData = input('post.document/a');
      //验证用户是否有权限修改数据
      if($request->cookie('login_code')!==$document->create_code){
        $this->error('仅文件创建者可修改,请联系管理员','read?id='.$id,"",2);
      }
      //下面进行数据有效性的验证
      $result=$this->validate($documentData,'Document');
      if(true !== $result){
        return $result;
      }
      // 保存图片类文件
      if($file = $request->file('pic')){
        $document->pic_name=$this->savePic($file);
      }
      // 下面设定document需要的属性,循环赋值;
      $target=array('title','detail','is_sth','sth_num','static',);
      foreach($target as $v){
        $document->$v=$documentData[$v];
      }
      if($document->allowField(true)->save()){
        $this->success('设计文件'.$document->code.":".$document->title.'修改成功! ','read?id='.$id,'',2);
      }else{
        $this->success('数据修改失败,请联系管理员','index');
      }
    }
    
    
    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit_process(Request $request,$id)
    {
      //验证Cookie↓
      $this->checkCookie();
      // 引入navbar
      $this->setNavbar();
      $this->assign('title',"设计文件流程处理");
      // 获取$document对象;
      $document=DocumentModel::get($id);
      $this->assign('document',$document);
      //  获取状态中最大值,count得到的包含状态0;
      $max_static_num=Db::name('moduleStatic')->where('module','document')->count()-1;
      // dump($max_static_num);
      //获取是否有documentProcess,没有则创建(仅文档的作者可以创建)
      if((1==$document->max_static && $request->cookie('login_code')==$document->create_code && !($processdata=$document->documentProcess))){
        $documentProcess = new DocumentProcess;
        $documentProcess->execute_code=$request->cookie('login_code');
        $documentProcess->execute_title=$request->cookie('login_name');
        $document->documentProcess()->save($documentProcess);
      }
      //获取已经保存的信息,没有则跳转到read
      if($saveProcess=$document->documentProcess()->where('is_fixed',0)->where('execute_code',$request->cookie('login_code'))->select()){
        $saveProcess=$document->documentProcess()->where('is_fixed',0)->where('execute_code',$request->cookie('login_code'))->select();
      }else{
        $this->redirect('read','id='.$id);
      }
      $this->assign('saveProcess',$saveProcess);
      // 从document_process中获取已完成信息
      $documentProcess=$document->documentProcess()->where('is_fixed',1)->order('id','asc')->select();
      $this->assign('documentProcess',$documentProcess);
      $this->assign('documentProcessNum',count($documentProcess));
      // 获取状态信息,用于填入到可选择的下一阶段可选择人员中
      $documentStaticList=ModuleStaticModel::where('module','document')->column('*','static');
      // 根据max_static来判断下一阶段处理人code,如果max_static最大,则默认值??
      // $process_id=$documentStaticList[$document->next_static]['process_id'];
      // $nextProcessId=$this->getNextProcessIdOld($process_id);
      //修改测试新的getNextProcessIdTest
      $nextProcessId=$this->getNextProcessId('document',$document->next_static);
      $this->assign('nextProcessId',$nextProcessId);
      return $this->fetch();
      // 如果max=11,最大,应该固定下一次人选
    }

    
    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update_process(Request $request, $id)
    {
      $document=DocumentModel::get($id);
      $decide=input('post.decide');
      $processdata=input('post.process/a');
      // 获取documentprocess对象
      if($saveProcess=$document->documentProcess()->where('execute_code',$request->cookie('login_code'))->where('is_fixed',0)->select()){
        $saveProcess=$document->documentProcess()->where('execute_code',$request->cookie('login_code'))->where('is_fixed',0)->select();
        // 将post的数据赋值给documentprocess对象
        foreach( $processdata as $k=>$v){
          $saveProcess[0][$k]=$v;
        }
        $processdata=$saveProcess[0];
      }else{
        $this->error('流程数据有误,失败代码167,请联系管理员','edit_process?id='.$id,"",2);
      }
      //  获取状态中最大值,count得到的包含状态0;
      $max_static_num=Db::name('moduleStatic')->where('module','document')->count()-1;
      // dump($max_static_num);
      if(0==$decide){
        // 保存:is_fixed不变,max_static不变,static不变
        $processdata['is_fixed']=0;
      }elseif(-1==$decide){
        // 返回:is_fixed=1,max_static不变,static=1
        $processdata['is_fixed']=1;
        $processdata['next_process_static']=1;
        $processdata['next_execute_code']=$document->create_code;
        $document->static=1;
      }elseif(1==$decide){
        // 确定:is_fixed=1,max_static看情况,static看情况
        $processdata['is_fixed']=1;
        if($document->static==$document->max_static){
          // 正常提交,max_static+1,static+1,next_static=max+1
          $processdata['next_process_static']=$document->max_static+1;
          $document->static=$document->max_static+1;
          $document->max_static=$document->max_static+1;
        }else{
          // 修改后返回,max_static不变,next_static=max,static=max;
          $processdata['next_process_static']=$document->max_static;
          $document->static=$document->max_static;
        }
      }
      //验证$processdata
      $result=$this->validate($processdata,'Process');
      if(true !== $result){
        return $result;
      }
      //验证Document
      $result=$this->validate($document,'Document');
      if(true !== $result){
        return $result;
      }
      // 保存$document
      if(0!=$decide && !($document->save())){
        $this->error('文件信息保存失败,失败代码161,请联系管理员','edit_process?id='.$id,"",2);
      }
      // 保存$processdata;
      if(!($processdata->save())){
        $this->error('文件记录保存失败,失败代码163,请联系管理员','edit_process?id='.$id,"",2);
      }
      // 确定是否是保存,并建立下一阶段数据
      if(0==$processdata['is_fixed']){
        // 仅仅是保存记录,跳转
        $this->redirect('edit_process','id='.$id);
      }elseif(1==$processdata['is_fixed'] && $document->max_static<$max_static_num){
        // 本阶段已经固定,并且不是最终阶段,新建下一阶段过程
        $nextprocessdata['execute_code']=$processdata['next_execute_code'];
        $nextprocessdata['process_static']=$processdata['next_process_static'];
        if(!($document->documentProcess()->save($nextprocessdata))){
          $this->error('文件后续记录无法进行,失败代码165,请联系管理员','edit_process?id='.$id,"",2);
        }else{
          $this->redirect('edit_process','id='.$id);
        }
      }
      // 当前记录已达到最大,流程结束
      if($document->max_static==$max_static_num){
        $this->redirect('read','id='.$id);
      }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
      //此处为彻底删除(还应该判断关联关系),入口在edit页面,'删除'实际上是更新,将static=0;
      $document=DocumentModel::get($id);
      $result=DocumentModel::destroy($id);       /* 可以使用delete方法 */
      if($result){
        $this->redirect('index');
      }else{
        $this->error('设计文件删除失败,请联系管理员','index');
      }
    }


}
